import network
import socket
import time
from html_page import get_html_index, get_html_alert
from set_gpio import led_status, set_io_value
import re
import machine


# 处理 HTTP 请求
def handle_request(conn):
    request = conn.recv(1024).decode()  # 接收客户端请求
    print("收到请求:\n", request)
    
    # 解析请求方法（GET/POST）
    if "GET / HTTP/1.1" in request:
        response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
        response += get_html_index()
    elif "GET /led/on HTTP/1.1" in request:
        led_status(True)
        response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
        response += get_html_index()
    elif "GET /led/off HTTP/1.1" in request:
        led_status(False)
        response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
        response += get_html_index()
    elif "GET /gpio/set" in request:
        request = request.split('\n')[0]
        match = re.search(r'pin=(\d+)&state=(\d+)', request)
        if match:
            pin = int(match.group(1))
            state = int(match.group(2))
            set_io_value(pin, state)
        response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
        response += get_html_alert(f"GPIO PIN{pin} SET {state} !")
    elif "GET /restart HTTP/1.1" in request:
        machine.soft_reset()  # 软复位（等同于reset）
        machine.hard_reset()  # 硬复位（部分固件支持）
    else:
        response = "HTTP/1.1 404 Not Found\r\n\r\n"
    
    conn.send(response.encode())  # 发送响应
    conn.close()

# 启动 HTTP 服务器
def start_http_server(sock):
    conn, addr = sock.accept()
    handle_request(conn)
